﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy.Messages;
using Tracy.Handlers;
using System.Xml;

namespace Tracy
{
    public partial class TaskScheduler
    {
        private int TICK_INTERVAL = 1000;
        //private int DEFAULT_TASK_INTERVAL = 5;

        private static System.Threading.Thread _workthread;

        private static readonly object _lockhelper = new object();

        private static bool _workthreadenabled = false;

        public bool WorkThreadEnabled
        {
            get { return _workthreadenabled; }
            set { _workthreadenabled = value; }
        }

        private bool _timerStarted;
        public bool TimerStarted
        {
            get { return _timerStarted; }
        }

        /// <summary>
        /// When On_Tick is called last time.
        /// </summary>

        private DateTime _lastcalled = DateTime.Now;
        /// <summary>
        /// Event when Scan is triggered.
        /// </summary>
        public event EventHandler<OnTaskTriggeredEventArgs> OnTaskTriggered;


        /// <summary>
        /// Be called every TICK_INTERVAL
        /// </summary>
        private void On_Tick()
        {
            DateTime now = DateTime.Now;
            double elapsed = (now - _lastcalled).TotalSeconds;
            foreach (TaskScheduler.Task scanToCheck in Tasks)
            {
                scanToCheck.Elapse(elapsed);
            }
            _lastcalled = now;
        }

        private void Task_OnTaskTriggered(object sender, TaskScheduler.OnTaskTriggeredEventArgs e)
        {
            if (OnTaskTriggered != null)
            {
                OnTaskTriggered(this, e);
            }
            //TODO: move to external logic??
            TaskMessage taskMsg = new TaskMessage(this, e.TaskItem.Handler, null);//TODO: callback?
            TracyFacade.Instance.MessageDispatcher.EnqueueMessage(taskMsg);
        }

        private void Run()
        {
            _timerStarted = false;
            while (WorkThreadEnabled)
            {
                _timerStarted = true;
                try
                {
                    System.Threading.Thread.Sleep(TICK_INTERVAL);
                    On_Tick();
                }
                catch (Exception ex)
                {
                    _timerStarted = false;
                    //TODO: throw new IDMIntegratedCore.Exceptions.IDMUnexpectedException(ex);
                }
            }
            _timerStarted = false;
        }

        #region "Public Interfaces"
        private static TaskList _tasks = new TaskList();
        /// <summary>
        /// Get the list of XSLT scans managed by XSLT manager
        /// </summary>
        public TaskList Tasks
        {
            get { return _tasks; }
        }

        public void RegisterTask(Task task)
        {
            if (!Tasks.Contains(task.Name))
            {
                Tasks.Add(task);
                task.OnTaskTriggered += new EventHandler<OnTaskTriggeredEventArgs>(Task_OnTaskTriggered);
            }
            
        }

        /// <summary>
        /// Load tasks from setting file
        /// </summary>
        /// <param name="settingfile">Setting file for XSLT scans</param>
        public void LoadSettings(string settingfile)
        {

            //Clear Scan Cache
            Tasks.Clear();

            XmlDocument doc = new XmlDocument();
            doc.Load("Settings\\TaskSchedule.xml");

            foreach (XmlElement node in doc.SelectNodes("/tasks/task"))
            {
                string name = node.GetAttribute("name");
                int interval = Int32.Parse(node.GetAttribute("interval"));
                string className = node.InnerText;

                Type taskType = Type.GetType(className);
                if (taskType != null)
                {
                    RegisterTask(new Task(name, taskType, interval));
                }
            }
        }

        public void StartTimer()
        {
            if (!_timerStarted)
            {
                _lastcalled = DateTime.Now;
                _workthread = new System.Threading.Thread(new System.Threading.ThreadStart(this.Run));
                WorkThreadEnabled = true;
                _workthread.Start();
                //Wait until timer started
                while (!(_timerStarted && _workthread.IsAlive))
                {
                    System.Threading.Thread.Sleep(100);
                }
                //IDMLogManager.Instance.Log("XSLT Scan Manager Timer Started");
            }
        }

        public void StopTimer()
        {
            if (_timerStarted)
            {
                WorkThreadEnabled = false;
                //Wait until timer stopped
                while (_timerStarted)
                {
                    System.Threading.Thread.Sleep(500);
                }
                _workthread = null;
                //IDMLogManager.Instance.Log("XSLT Scan Manager Timer Stopped");
            }
        }
        #endregion


        public class OnTaskTriggeredEventArgs : EventArgs
        {

            private TaskScheduler.Task _task;
            public TaskScheduler.Task TaskItem
            {
                get { return _task; }
            }

            public OnTaskTriggeredEventArgs(TaskScheduler.Task task)
            {
                _task = task;
            }
        }
    }
}
